<template>
  <div class="login">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>后台管理系统</span>
      </div>

      <el-form 
      ref="form" 
      :model="form" 
      label-width="80px"
      >
        <el-form-item label="用户名" prop="username"
        :rules="[
            {required:true , message:'请输入用户名' , trigger: 'blur'},
            {min: 4 , max: 10 , message:'长度在4-10位字符之间' , trigger: 'blur'}
        ]"
        >
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password"
        :rules="[
            {required:true , message:'请输入密码' , trigger: 'blur'},
            {min: 6 , max: 12 , message:'长度在6-12位字符之间' , trigger: 'blur'}
        ]"
        >
          <el-input v-model="form.password" type="password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="tologin(form)">登录</el-button>
        </el-form-item>
        
      </el-form>
    </el-card>
  </div>
</template>

<script>
import {login} from '@/api/index.js'
import {setToken} from '@/util/token.js'
export default {
  name: "login",
  data() {
    return {
      form: {
        username: "",
        password: "",
      },
    };
  },
  methods: {
    tologin(){
        login(this.form).then(res=>{
          console.log(res.data);
          if(res.data.status === 200){
            //保存token到localStorage
            setToken('username' , res.data.username)
            setToken('token' , res.data.token)
            this.$message({
              message: '登录成功',
              type: 'success'
            });
            this.$router.push('/home')
          } else{
            this.$message({
              message: '用户名或密码不符合格式',
              type: 'error'
            });
          }
          
        })
    }
  },
};
</script>

<style scoped lang="less">
.login {
  width: 100%;
  height: 100%;
  background-color: aquamarine;
  display: flex;
  justify-content: center;
  align-items: center;
  .box-card {
    width: 450px;
    height: 300px;
    text-align: center;
    border-radius: 20px;
  }
  .el-button--primary {
    width: 100%;
  }
}
</style>
